"""
pip install PyJWT
"""
import jwt
from jwt.exceptions import DecodeError, ExpiredSignatureError
from django.conf import settings
import datetime
import logging

logger = logging.getLogger('django')

# 获取Django的密钥
# SECRET_KEY = 'django-insecure-2cvu_ew%s2&(3+ex7dn=gs@(4dv_)o5=81(q!4(h+_4eua7-7%'
SECRET_KEY = settings.SECRET_KEY


# 生成JWT token
def generate_jwt_token(payload, expire_second):
    expires_in = datetime.datetime.utcnow() + datetime.timedelta(seconds=expire_second)
    payload.update({
        'exp': expires_in
    })
    jwt_token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return jwt_token


# 校验JWT token
def checkout_token(token):
    try:
        decode_token = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
    except (DecodeError, ExpiredSignatureError) as e:
        logger.warning(f"JWT decode error: {e}")
        return False
    else:
        decode_token.pop('exp')
        return decode_token


if __name__ == '__main__':
    import time
    token = generate_jwt_token({"name": 12}, 3)
    print(f"生成的token: {token}")

    time.sleep(2)
    print(f"token校验结果: {checkout_token(token)}")
